package com.tosh;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

/**
 * User: arsentyev
 * Date: 02.08.12
 */
public class ClassPathResource {
    private final String path;
    private ClassLoader classLoader;
    private Class clazz;

    public ClassPathResource(String path) {
        this(path, (ClassLoader) null);
    }

    public ClassPathResource(String path, ClassLoader classLoader) {
        if (path.startsWith("/")) {
            path = path.substring(1);
        }
        this.path = path;
        this.classLoader = (classLoader != null ? classLoader : ClassLoader.getSystemClassLoader());
    }

    public ClassPathResource(String path, Class clazz) {
        this.path = path;
        this.clazz = clazz;
    }

    protected ClassPathResource(String path, ClassLoader classLoader, Class clazz) {
        this.path = path;
        this.classLoader = classLoader;
        this.clazz = clazz;
    }


    public final ClassLoader getClassLoader() {
        return (this.classLoader != null ? this.classLoader : this.clazz.getClassLoader());
    }


    public InputStream getInputStream() throws IOException {
        InputStream is = null;
        if (this.clazz != null) {
            is = this.clazz.getResourceAsStream(this.path);
        } else {
            is = this.classLoader.getResourceAsStream(this.path);
        }
        if (is == null) {
            throw new FileNotFoundException();
        }
        return is;
    }
}